﻿using Ninject;
using Ninject.Parameters;
using Ninject.Syntax;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;

namespace HobSoft.SoccerBet2014.Domain.Common.Factory
{
    using Domain.Common.Site;
    using Domain.Common.SiteContext;
    using Domain.Core;
    using Domain.DataService;
    using Domain.Factory;

    public class SiteManagerFactory : IBetSiteManagerFactory
    {
        private static Dictionary<byte, Type> siteManagerImpl = new Dictionary<byte, Type>();
        private static ConcurrentDictionary<string, IBetSiteManagerService> managerCache = new ConcurrentDictionary<string, IBetSiteManagerService>();

        static SiteManagerFactory()
        {
            siteManagerImpl.Add(10, typeof(IbcSessionManager));
            siteManagerImpl.Add(11, typeof(SboSessionManager));
            siteManagerImpl.Add(12, typeof(HgSessionManager));
        }


        private readonly IResolutionRoot _resolutionRoot;

        public SiteManagerFactory(IResolutionRoot resolutionRoot)
        {
            _resolutionRoot = resolutionRoot;
        }

        public IBetSiteManagerService CreateOrGet(byte bmId, string account, string globalHost)
        {
            if (!siteManagerImpl.ContainsKey(bmId))
                throw new NotImplementedException(string.Format("没有实现bmId为{0}的SessionManager", bmId));
            var type = siteManagerImpl[bmId];
            string key = string.Format("{0}|{1}|{2}", bmId, account, globalHost);

            if (managerCache.ContainsKey(key))
                return managerCache[key];

            var impl = _resolutionRoot.Get(type
                                    , new ConstructorArgument("cookiesManager", _resolutionRoot.Get<ICookiesManager>())
                                    , new ConstructorArgument("repositoryService", _resolutionRoot.Get<IBetGameDataService>())
                                    , new ConstructorArgument("globalHost", globalHost)
                                    , new ConstructorArgument("bookerId", bmId)
                                    , new ConstructorArgument("account", account));
            var manager = (SessionManagerBase)impl;
            managerCache.TryAdd(key, manager);
            return manager;


        }

        public IBetSiteManagerService CreateOrGet()
        {
            return _resolutionRoot.Get<SessionManagerBase>();
        }

        object IServiceFactory.CreateOrGet()
        {
            return _resolutionRoot.Get<SessionManagerBase>();
        }
    }

}
